<?php
namespace Home\Controller;
use Think\Page;
class VideosController extends MemberController{

	// 构造函数
	public function _initialize(){
		parent::_initialize();
		$this->db = D('Videos');
		$this->category_cache = S('Category');
	}

	/**
	 * [info 视频播放]
	 * @return [type] [description]
	 */
	public function info(){
		// 获取ID
		$id = $_GET['id'];
		$video_info = $this->db->where(array('video_id'=> $id))->find();
		// 判断视频是否存在
		if (empty($video_info)) {
			$this->error('非法访问，该视频不存在',U('Index/index'));
			return false;
		}
		if ($video_info['status'] == 0) {
			$this->error('请等待管理员审核该视频',U('Index/index'));
			return false;
		}
		// 获取视频信息
		$video_info = $this->db->GetVideoKey($video_info);
		// 生成视频当前地址
		$video_info['url'] = U('Home/Videos/info',array('id'=> $video_info['video_id']));
		// 增加播放次数
		$this->db->where(array('video_id'=> $id))->setInc('play_times',1);
		// 分配数据
		$this->assign('seo_title', $video_info['video_title']);
		$this->assign('video_info', $video_info);
		$this->display();
	}

	// 视频列表
	public function index(){
		$where['video_uid'] = $this->user_uid;
		// 统计数据总数
        $count = $this->db->where($where)->count();

        // 实例化分页类 传入总记录数和每页显示的记录数
        $page = new Page($count,10);

        // 样式制定
        $page->lastSuffix = false;
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $page->setConfig('header', '共 <span class="text-red">%TOTAL_ROW%</span> 个视频');
        $page->setConfig('theme', '%UP_PAGE% %FIRST% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER% 总 <span class="text-red">%TOTAL_PAGE%</span> 页');
        // 显示数据分页
        $show = $page->show();
		// 获取视频信息
		$data = $this->db->relation(true)->where($where)->order('create_time desc')->limit($page->firstRow.','.$page->listRows)->select();
		$video_status = C('VIDEO_STATUS');
		$this->assign('page', $show);
		$this->assign('data', $data);
		$this->assign('video_status', $video_status);
		$this->display();
	}
	// 视频上传
	public function add(){
		$this->display();
	}
	// 视频编辑
	public function edit(){
		if (IS_POST) {
			if ($this->db->VideoSave()) {
				$this->success('视频编辑操作成功');
			}else{
				$this->error($this->db->getError());
			}
		}else{
			// 获取HASH与KEY
			$video_key = $this->KeyHash();
			$info_name = $_GET['info_name'];
			// 判断GET中是否存在KEY
			if (empty($video_key)) {
				$this->error('非法访问，不存在的视频ID',U('Videos/index'));
				return false;
			}
			// 获取视频信息
			$video_info = $this->Video_info($video_key, $info_name);
			// 判断视频是否存在
			if (empty($video_info)) {
				$this->error('非法访问，该视频不存在');
				return false;
			}
			$this->assign('video_info', $video_info);
			$this->display();
		}
	}

	/**
	 * [VideoAdd 视频检测添加]
	 * @param string $key         [description]
	 * @param string $hash        [description]
	 * @param string $video_title [description]
	 */
	public function VideoAdd($key = '', $video_title = ''){
		$video_info = $this->video_data_info($key);
		// 判断是否新上传视频
		if (!empty($key) && $key != 'no') {
			// 获取请求的KEY
			$key_info = empty($video_info['video_high_key']['items'][0]['key']) ? $key : $video_info['video_high_key']['items'][0]['key'];
			// 获取七牛视频数据
			$qiniu_video_info = GetVideoInfo($key_info);
			// 判断是否新视频，如果是，则写入数据库
			if (!empty($qiniu_video_info) && !$this->db->where(array('video_key'=> $key, 'video_uid'=> $this->user_uid))->field('video_id')->find()) {
				// 删除视频组合名
				$video_title = substr($video_title,0,strlen($video_title)-4);
				// 对视频进行转码
				$video_transcoding = CreateVideoAvthumb($key, 'player');
				if (is_array($video_transcoding)) {
					foreach ($video_transcoding as $k => $v) {
						$video_data[$k] = $v;
					}
				}
				// 重组新数据
				$video_data['video_uid'] = $this->user_uid;
				$video_data['video_cid'] = 1;
				$video_data['video_key'] = $key;
				$video_data['create_time'] = time();
				$video_data['video_title'] = $video_title;
				// 视频截图ID
				$create_img_id = CreateVideoImg($key, 'player');
				if (is_array($create_img_id)) {
					$video_data['video_thumb_id'] = $create_img_id['id'];
				}				
				// 数据入库
				$video_id = $this->db->add($video_data);
				$this->redirect('Home/Videos/edit', array('id'=> $video_id, 'key'=> $key));
			}else{
				return $video_info;
			}
		}else{
			return $video_info;
		}
	}

	/**
	 * [video_data_info 查询数据库的视频数据]
	 * @return [type] [description]
	 */
	public function video_data_info($key = ''){
		// 组合查询条件
		isset($key) ? $video_where['video_key'] = $key : '';
		isset($_GET['id']) ? $video_where['video_id'] = $_GET['id'] : '';
		$video_where['video_uid'] = $this->user_uid;
		$video_info = $this->db->where($video_where)->find();
		// 查询视频转码KEY
		$video_info = $this->VideoKeyStatus($video_info);
		// 获取缩略图
        $video_info = $this->ThumbInfo(object_array(json_decode(file_get_contents("http://api.qiniu.com/status/get/prefop?id=".$video_info['video_thumb_id']))), $video_info);
        // 返回数据
		return $video_info;
	}

	/**
     * [ThumbInfo 视频缩略图信息]
     * @param string $thumbinfo  [description]
     * @param string $video_info [description]
     */
    public function ThumbInfo($thumbinfo = '',$video_info = ''){
    	// 再次系统截图
    	if (empty($video_info['video_thumb_id'])) {
    		$create_img_id = CreateVideoImg(empty($video_info['video_high_key']['items'][0]['key']) ? $video_info['video_key'] : $video_info['video_high_key']['items'][0]['key'], 'player');
    		$this->db->where(array('video_id'=> $video_info['video_id']))->save(array('video_thumb_id'=> $create_img_id['id']));
    	}
        // 0 表示成功，1 表示等待处理，2 表示正在处理，3 表示处理失败，4 表示回调失败。
        switch ($thumbinfo['items'][0]['code']) {
            case 0:
                $video_info['error'] = '截图成功';
            break;
            case 1:
                $video_info['error'] = '等待截图';
            break;
            case 2:
                $video_info['error'] = '正在截图';
            break;
            case 3:
                $create_img_id = CreateVideoImg(empty($video_info['video_high_key']['items'][0]['key']) ? $video_info['video_key'] : $video_info['video_high_key']['items'][0]['key'], 'player');
                $this->db->where(array('video_id'=> $video_info['video_id']))->save(array('video_thumb_id'=> $create_img_id['id']));
                $video_info['error'] = '截图失败';
            break;
            case 4:
                $video_info['error'] = '截图回调失败';
            break;
            
            default:
                $video_info['error'] = '截图出现错误';
            break;
        }
        if ($thumbinfo['items'][0]['code'] == 0) {
        	$video_info['thumb_path'] = isset($thumbinfo['items'][0]['key']) ? C('QINIU_DOMAIN') . $thumbinfo['items'][0]['key'] : '';
        }else{
            $video_info['message'] = $thumbinfo['items'][0]['error'];
        }
        return $video_info;
    }

	/**
	 * [VideoKeyStatus 获取转码后的KEY]
	 * @param string $video_key [description]
	 */
	public function VideoKeyStatus($video_info = ''){
		if (!empty($video_info['video_sd_id']) && !empty($video_info['video_high_id']) && !empty($video_info['video_super_id'])) {
			$video_info['video_sd_key'] = VideoKeyStatus($video_info['video_sd_id'], 'player');
			$video_info['video_high_key'] = VideoKeyStatus($video_info['video_high_id'], 'player');
			$video_info['video_super_key'] = VideoKeyStatus($video_info['video_super_id'], 'player');
			if (!empty($video_info['video_high_key']['items'][0]['key'])) {
				$video_info['default_key'] = $video_info['video_high_key']['items'][0]['key'];
			}else{
				$video_info['default_key'] = $video_info['video_key'];
			}
			// 返回KEY
			return $video_info;
		}
	}

	/**
	 * [Video_info 获取视频信息]
	 * @param [type] $key       [description]
	 * @param [type] $info_name [description]
	 */
	public function Video_info($key, $info_name){
		return $this->VideoAdd($key, $info_name);
	}

	/**
	 * [KeyHash 获取KEY与HASH]
	 */
	public function KeyHash(){
		if (empty($_GET['key']) && $_GET['key'] != 'no') {
			return $_GET['hash'];
		}else{
			return $_GET['key'];
		}
	}

	/**
	 * [VideoZhuanma 查询七牛转码状态]
	 */
	public function VideoZhuanma(){
		$qiniu_video_info['video_sd_status']		= VideoKeyStatus($_GET['video_sd_id'], 'player');
		$qiniu_video_info['video_high_status']		= VideoKeyStatus($_GET['video_high_id'], 'player');
		$qiniu_video_info['video_super_status']		= VideoKeyStatus($_GET['video_super_id'], 'player');
		// 状态码0成功，1等待处理，2正在处理，3处理失败，4通知提交失败。
		switch ($qiniu_video_info['video_sd_status']['code']) {
			case 0:
				$video_info['video_sd_status']['zhuanma_info'] = '标清转码完成';
			break;
			case 1:
				$video_info['video_sd_status']['zhuanma_info'] = '等待标清转码';
			break;
			case 2:
				$video_info['video_sd_status']['zhuanma_info'] = '正在标清转码';
			break;
			case 3:
				$video_info['video_sd_status']['zhuanma_info'] = '标清转码失败';
			break;
			case 4:
				$video_info['video_sd_status']['zhuanma_info'] = '提交标清转码失败';
			break;
			
			default:
				$video_info['video_sd_status']['zhuanma_info'] = '标清转码出现错误';
			break;
		}
		switch ($qiniu_video_info['video_high_status']['code']) {
			case 0:
				$video_info['video_high_status']['zhuanma_info'] = '高清转码完成';
			break;
			case 1:
				$video_info['video_high_status']['zhuanma_info'] = '等待高清转码';
			break;
			case 2:
				$video_info['video_high_status']['zhuanma_info'] = '正在高清转码';
			break;
			case 3:
				$video_info['video_high_status']['zhuanma_info'] = '高清转码失败';
			break;
			case 4:
				$video_info['video_high_status']['zhuanma_info'] = '提交高清转码失败';
			break;
			
			default:
				$video_info['video_high_status']['zhuanma_info'] = '高清转码出现错误';
			break;
		}
		switch ($qiniu_video_info['video_super_status']['code']) {
			case 0:
				$video_info['video_super_status']['zhuanma_info'] = '超清转码完成';
			break;
			case 1:
				$video_info['video_super_status']['zhuanma_info'] = '等待超清转码';
			break;
			case 2:
				$video_info['video_super_status']['zhuanma_info'] = '正在超清转码';
			break;
			case 3:
				$video_info['video_super_status']['zhuanma_info'] = '超清转码失败';
			break;
			case 4:
				$video_info['video_super_status']['zhuanma_info'] = '提交超清转码失败';
			break;
			
			default:
				$video_info['video_super_status']['zhuanma_info'] = '超清转码出现错误';
			break;
		}
		$this->ajaxReturn($video_info, 'json');
	}

	// 操作视频状态
	public function video_status_save(){
		if (IS_AJAX) {
			# code...
		}else{
			$this->error('非法操作，请重新尝试');
		}
	}
	// 视频删除
	public function del(){
		$this->display();
	}
}